- Special Edition Using Visual Basic Script -

CHAPTER 13 - Comparing VBScript, VBA, and Visual Basic

by Ron Schwarz


This chapter addresses the differences you'll encounter when coming to VBScript from a background in one of the "traditional" VB dialects (VB/VBA).

Overview

Because VBS is a subset of VB, the bulk of the information provided in here consists of differencesùmainly differences of omissionùas documented by Microsoft at the time this book goes to press. (Some of this may change eventuallyùthe VBS specifications have changed more than once since work began on this book, but are expected stabilize shortly.)

Syntactical differences, covered in Table 13.1, Declaration Issues, and Table 13.2, Language Issues, are only part of the picture. If you're going to excel in what you're doing, you need to learn the nuances of the platform and accommodate yourself to it.

Trying to "force-fit" either existing code or existing skills to a new environment is tantamount to the backwoods axiom that advises, "Don't force it, use a bigger hammer!" Even if you do succeed in fitting the square peg to the round hole, neither you, nor your users are apt to be particularly satisfied with the results.

Therefore, it's an absolute necessity that you gear yourself to the language (VBScript) ,the development tools at hand (ActiveX Control Pad), and the presentation medium (Internet Explorer).

If you're a VB programmer, you can probably remember muddling through the documentation, the IDE, and the language, making small headway until things suddenly "clicked," and it started making sense. This event marked the beginning of your ability to "think in VB," and you can expect a similar illumination after playing with VBS and the Control Pad for a while.

Naturally, you will be able to leverage a considerable measure of your existing skills and language. But, it will quickly become apparent that VBS has its own gestalt. It's not too different from situations that occur with spoken language: Cantonese and Mandarin are both "Chinese," but fluency in one does not equate to fluency in the other. So it is with VBS and the other dialects of VB.

You'll find some of the differences maddening at first, but the frustration will diminish as you begin to work instinctively.

There are two main reasons for omitted functionality. The first consideration is security (it would be poor form to make it easy for unscrupulous individuals to harm users who stumble upon their websites), and "weight" (because of issues such as download time and memory footprint, VBS is designed to be a "lightweight" implementation of the language).

Declaration Comparison

Table 13.1 covers the declaration changes documented by Microsoft. If you're experienced with one of the other dialects of VB (VB or VBA) you should take the time to familiarize yourself with the differences now, to avoid frustration later on.

Table 13.1 Declaration Issues

Declaration Issues
Declare DLL API calls are not implemented due to security considerations, and because VBScript is intended to be a cross-platform language. (Windows-specific API calls would fail on a browser running on a non-Windows OS.)
Property Get Not applicable due to absence of Class creation support in VBS.
Property Let Not applicable due to absence of Class creation support in VBS.
Property Set Not applicable due to absence of Class creation support in VBS.
Public (variables) Not currently supportedùconflicting information available. May be implemented in final release.
Private (variables) Not currently supportedùconflicting information available. May be implemented in final release.
Static Use global variables when you need to retain contents between invocations of a procedure.
ParamArray Optional arguments not legal.
Optional Optional arguments not legal.
New Not possible to create new objects. Only legal to create aliases to existing instances of objects.
Array function Not supported. Use explicit assignments of each element of an array to load with values.
Option Base Not supported. All arrays have starting subscript of 0.
Private (procedures) Not currently supportedùconflicting information available. May be implemented in final release.
Public (procedures) Not currently supportedùconflicting information available. May be implemented in final release.
Dim (arrays) You cannot use the Dim Array(LowerBound To HigherBound) form of the Dim statement. All arrays begin with a 0 subscript. You can create a multi-dimensional array, but all dimensions must begin with an implied element 0.
Const Constants are not supported in VBScript. Use variables, and for convenience, make their names all uppercase, with words separated by an underscore, in other words, MAX_USER_COUNT. Note that this will not make a variable into a constantùyou will not be protected from inadvertently changing the value of the variable. It is strictly a means for identifying variables that are being used as ersatz constants.
Built-in Constants The only built-in constants currently implemented in VBScript are True and False.
Dim X As The As keyword is not supported because in VBScript all variables are of Variant type. It is likewise illegal to append a type-declaration character (such as !, @, #, $, %, &) to a variable or literal. Hence, both VehicleYear% and 1967% are illegal.

While not all VB funtionality is supported in VBScript, implemented features are fortunately highly compatible with their VB counterparts. This behavior carries over to most language elements, covered in the next section, "Language Comparison."

Language Comparison

Table 13.2 lists the changes in language elements at the time this book goes to press. There are significant differences between VB/VBA and VBScript. The changes are essentially changes of ommissionùwhile you will need to learn what to avoid, you won't have to relearn any implemented features, since syntax remains consistent.

Table 13.2 Language Issues

Term Explanation
Add User-defined collections are not supported in VBScript.
Count User-defined collections are not supported in VBScript.
Item User-defined collections are not supported in VBScript.
Remove User-defined collections are not supported in VBScript.
! (for Collections) User-defined collections are not supported in VBScript.
#Const, #If...Then...#Else Conditionals are not supported in VBScript.
DoEvents Not supported.
For Each...Next Not supported. Determine actual quantity being counted (i.e., array UBound), and use a For..Next loop structure instead.
GoSub ... Return Not supportedùline labels are not supported in VBScript.
GoTo Not supportedùline labels are not supported in VBScript.
On Error GoTo Not supportedùline labels are not supported in VBScript.
On ... GoSub Not supportedùline labels are not supported in VBScript.
On ... GoTo Not supportedùline labels are not supported in VBScript.
Line Numbers, Labels Not supported in VBScript. (Line Labels are not be confused with Label controls, which are implemented via ActiveX controls.)
With ... End With Not supportedùuse fully-qualified Object.Property names instead.
CCur Not supported (Currency subtype not implemented in VBScript).
CVar Not supported, all variables are Variant in VBScript.
CVDate Not required because there is a built-in Date subtype in VBScript. Was only included in VB4 for backward-compatibility reasons.
Format Not supported. Use String manipulation functions to build formatted strings as a workaround.
Str Not implemented in VBScript.
Val Not implemented in VBScript.
Type ... End Type Typed records are not implemented in VBScript.
Date Statement The Date function is implemented in VBScript, but the Date statement is not. (The function returns the current date; the statement sets the system clock.)
Time Statement The Time function is implemented in VBScript, but the Time statement is not. (The function returns the current time; the statement sets the system clock.)
Timer The Timer function is not implemented in VBScript. This should not be confused with the Timer control, which is implemented (via an ActiveX control). The Timer function returns the number of seconds that have elapsed since midnight; equivalent functionality can be derived by using the date/time math functions for whatever purpose the Timer function would have produced (i.e., start/end time logging).
LinkExecute Not implementedùVBScript does not offer DDE support.
LinkPoke Not implementedùVBScript does not offer DDE support.
LinkRequest Not implementedùVBScript does not offer DDE support.
LinkSend Not implementedùVBScript does not offer DDE support.
Debug.Print The Debug object is not implemented in VBScript because there is no means to execute a script within an IDE. (The ActiveX Control Pad provides a development environment, but it does not support running scripts within itself.)
End Not implemented in VBScript. Inapplicable in non-standalone (i.e., browser-hosted) applications.
Stop Not implemented, because there is no debug object in VBScript. There is no means to execute a script within an IDE. (The ActiveX Control Pad provides a development environment, but it does not support running scripts within itself.)
Erl Not implemented in VBScript; line numbers are not supported in VBScript.
Error Old-style error-handling keyword is not implemented in VBScript. Use the Error object's Raise method instead.
On Error ... Resume Not implemented in VBScript. On Error Resume Next is the only error-recovery structure available in VBScript (besides the Error object).
Resume Not implemented in VBScript. On Error Resume Next is only error-recovery structure available in VBScript (besides the Error object).
Resume Next Not implemented in VBScript. On Error Resume Next is the only error-recovery structure available in VBScript (besides the Error object).
Open ... Close No file I/O statements or functions are implemented in VBScript due to security considerations.
Get/Put No file I/O statements or functions are implemented in VBScript due to security considerations.
Input # No file I/O statements or functions are implemented in VBScript due to security considerations.
Print # No file I/O statements or functions are implemented in VBScript due to security considerations.
Write # No file I/O statements or functions are implemented in VBScript due to security considerations.
Financial Functions No financial functions are implemented in VBScript.
GetObject Not implemented in VBScript due to security considerations.
TypeOf Not implemented in VBScript. Use IsType when necessary to test against specific subtypes.
Clipboard Not implemented in VBScript due to security considerations.
Collection Not implemented in VBScript.

Like (Operators)

Deftype Not implemented in VBScriptùall variables are of Variant type.
Option Base Not implemented in VBScriptùall arrays begin with a subscript of 0.
Option Compare Not implemented in VBScript. Use StrComp options as a workaround.
Option Private Module Not supported. (No modules in VBScript)
Fixed-length strings Not supported in VBScript. If absolutely required, use standard (variable-length) strings, and pad with spaces to desired length using Space().
Lset Not supported in VBScript.
Rset Not supported in VBScript.
Mid Statement Not supported in VBScript. Do not confuse the Mid statement with the Mid function. The function form of Mid is used to read characters within a string; the (currently unsupported) statement form is used to insert characters into a string.
StrConv Not implemented in VBScriptùLCase and UCase can be used to provide vbLowerCase and vbUpperCase functionality.
TypeName Not implemented in VBScriptùall variables are of Variant type.

As you can see from Table 13.2, there are quite a few VB features that are unimplemented in VBScript. The reasons are threefold: VBScript is designed to be a lightweight language for performance and resource reasons, it's necessary to prevent potential for damage via "dangerous" functions, and, the Web page platform has different characteristics than a VB program. The next section, "Style Differences," shows you how to accommodate yourself to the differences covered so far in this chapter.

Style Differences

Just as VB programming requires a change in philosophy from non-GUI programming, creating script-enabled Web pages hosted in a WWW browser mandates a new way of thinking and coding. To further complicate matters, the Internet is undergoing a series of concurrentùand majorùtransformations. If change indeed brings opportunity, the Internet is likewise what might be termed a "target-rich environment." It has lots of potential, and it has lots of risk. Surfing the Web is more accurate an aphorism than it might seem; the trick is to stay on top of the wave.

If you come from a traditional HTML programming background, your head is probably spinning about now. It'll pass. The Web will remain content-heavy, but the fantastic array of ActiveX controls, combined with HTML Layout Page functionality will provide the ability to do more than ever before, and to do it easier than you ever imagined. You'll have to learn to think in new ways, and at first, you'll need to resist the temptation to do things the old way. As long as the traditional HTML methods are more familiar to you than the new ActiveX features, you'll have to discipline yourself to work with the new capabilities, but it will be worth it in the long run, and besides, it won't take that long.

VB programmers, on the other hand, will probably feel like they're back in the training-wheel stage. To an extent, it's an accurate perception: VBS is rather limited when compared to VB 4.0. But, unlike traditional VB programming, where the program is the totality of your efforts, or even VBA development, where you have freedom from language and security restrictions, VBScript applications are documents, and the code itself takes a role subservient to the end product.The changes of style affect you, as a developer, and, they affect the people who use what you write. Whether you're creating Internet pages, used by anyone who stumbles onto your site, or vertical-market intranet systems, you'll have to conform yourself to the realities and requirements of the medium, and the needs and expectations of the users.The following sections focus on the issues you'll need to keep in mind when working with VBScript.

Development Environment

The ActiveX Control Pad (covered in detail in Chapters 3-5) provides an excellent platform for creating script-enabled Web pages. However, convenient and powerful as it may be, it is not a full-featured IDE. In addition to the features that are available in VB, but are not present in the Control Pad, you'll have to deal with the "look and feel" differences, and limitations imposed by the target platform.

Error Control

The area that is perhaps most notable in its absence is any type of debugging facility. Because scripts are only one part of a page, it may be some time before there's much debugging capability built-in to VBS development tools. (When you reflect on the complexity of the Internet Explorer, and consider that any debugger worth its salt would have to emulate the IE, in addition to being able to interpret VBScript with the level of detail offered by VBùbreakpoints, single-step, expression watches, etc.ùit becomes apparent that the undertaking would bemonumental.)

This being acknowledged, you do still have to deal with debugging issues, and the onus is entirely on you at this stage of the game. What to do? First and foremost, read Appendix C, "VBScript Coding Conventions," and take its message to heart. By rigorously adhering to a set of standards, your code will be readable and understandable, and as a result, you'llbe better prepared to comprehend it later on.

Use Option Explicit to help prevent errors caused by typos. Yes, even with Option Explicit turned on, you won't find undeclared variables until you're running your page in the Internet Explorer, but at least you will find them.

Layout Management

When you're first learning VBScript, you'll probably experiment with Notepad, or an equivalent ASCII text editor. It's a fast, easy way to enter a few lines of code and save them to a file. However, once you begin to gain an understanding of ActiveX "stuff" (of which VBScript is but one part), you'll need to make the transition to the ActiveX Control Pad.

While it's true that anything the Control Pad can do interactively, you can do manually in Notepad, it's also true that you can walk from New York to California. This is especially important to remember if you're really good in HTML, because you will have to consciously depart from familiar territory to something completely new and alien.

It's likely that HTML as we know it is dead. It may not know it's dead, and maybe a lot of HTML-oriented folks don't know it's dead either. But, that doesn't change the reality that the new Layout Page flexibility has been needed for some time, and is finally available. HTML will remain as the underlying container, but the old-style flow-of-text formatting is gone, gone, gone, once ActiveX takes hold.

Why is this such a big deal?

Consider for a moment the confusion that surrounds HTML. The proliferation of new, proprietary formatting codesùeverything from special font handling commands to table codes (and everything in between) exists to provide a measure of control over the appearance of the final product. The fact that it's possible at all, given the underlying formatting model, is a testament to the ability of the people writing browser software.

But, it's resulted in language-bloat of gargantuan proportion. It's hard to believe that anyone is proficient in the near-countless codes, let alone the variations between one browser and another.

The "big deal" is this: HTML Layout Pages provide a simple, elegant, and workable solution to the problems of placing, sizing, and formatting content and active elements in a web page. They sweep away the need for the vast majority of HTML arcana, and render much of it functionally obsolete. If it was a movie, it would be called, "Buggy-whip manufacturers vs. the Model T Redux."

The moral is, don't be so attached to the old way of doing things that you miss out on the opportunity that the new technology presents. It can become a personal issue, especially if you are proficient in the existing system, but don't make the same mistake that so many have before during times of change. Remember the countless programmers who stayed with CP/M, because they thought, "MSDOS will never make it," or, the ones who stayed too long at the C: prompt, because "Windows? Who needs it!".

It's good to learn from your mistakes. It's better to learn from the mistakes of others. Remember: the trick is to stay on top of the wave.

User Environment

When desktop publishing software first became widely available, there was a wave of what were snickeringly referred to as "Ransom Notes"ùdocuments with numerous typefaces and sizes all on one sheet. People went wild playing with fonts, pitches, attributes, and formatting. Everyone became an instant typesetter. People who should have been managing operations instead spent their time playing at "publishing," and simple memos turned into major productions, replete with grammatical and spelling errors galore.

Marshall McCluhan said, "The medium is the message." The sad fact is, people naturally tend to get wrapped up in the glitz and trappings of something new, especially when that something is a graphical presentation system.

While this book can't cover everything you'll ever need to know about style, layout, and presentation, it can at least give you some pointers, and aim you in the right direction.

The first bit of advice is simple. Simple, as in "Keep It Simple." Resist the temptation to do everything, everywhere, every time. You don't really have to use every last feature offered by ActiveX and VBS in each project you create. To be sure, the temptation will be thereùwhen it's easy to drop a group of controls into a tabbed container, and surround it with buttons and pictures and... You get the idea. Present the users with what needs to be presented, in a visually attractive manner, without overwhelming them. Sensory overload is not a pretty sight.

One of the best sources of design insight is available to you immediately. Take a look at the different types of web pages that are posted on thenet. As of late, Microsoft seems to be paying particular attention to design issues, and, they seem to be doing a good job of it. Their pages are logical, relatively fast loading, and contain quite a bit of content without appearing "busy" or confusing.

Other sites go to the other extreme. You've probably landed at one time or another on a page that took fifteen minutes to load, and consisted of miles of links and random bitmaps all arranged in an incredibly long single column down one drawn-out page.

Some general, and near universal rules are easy to follow: avoid clutterùdon't cram large numbers of controls on one page. If it's really necessary to have a lot of controls, use a tabbed container, and place the controls on tabs according to logical considerations. Try to put yourself in the place of the users. Remember that having thought up, written, debugged, and tested your project, you are intimately familiar with it in its entirety, but, a user dealing with it for the first time will find it all new, and no matter how well-designed it is, a bit intimidating.

The fallacy in our field is the notion that as software becomes increasingly powerful, it becomes increasingly difficult to use. The best illustration of the falsehood of this statement is the new change that is taking over Web programming. It's changing from something of finite capability and incredible complexity, to something of limitless potential, and less and less effort.

From Here...

For all the similarities between VB and VBScript, it is truly a major new approach to programming. The following resources will prove very valuable.


| Previous Chapter | Next Chapter |

| Search | Table of Contents | Book Home Page | Buy This Book |

| Que Home Page | Digital Bookshelf | Disclaimer |


To order books from QUE, call us at 800-716-0044 or 317-361-5400.

For comments or technical support for our books and software, select Talk to Us.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.